package com.gel.aiagent.app;

import com.gel.aiagent.advisor.MyLoggerAdvisor;
import com.gel.aiagent.chatmemory.FileBasedChatMemory;
import com.gel.aiagent.rag.LoveAppRagCustomAdvisorFactory;
import com.gel.aiagent.rag.QueryRewriter;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Slf4j
@Service
public class LoveApp {
    private final ChatClient chatClient;
    @Resource
    private  VectorStore loveAppVectorStore;
    @Resource
    private Advisor  loveAppRagCloudAdvisor;
    @Resource
    private  VectorStore pgVevctorVectorStore;
    @Resource
    private QueryRewriter  queryRewriter;
    @Resource
    private ToolCallback[]  allTools;
    @Resource
    private ToolCallbackProvider toolCallbackProvider;
    @Resource
    private ChatMemory chatMemory;

    @PostConstruct
    public void init() {
        log.info("init");
    }
    private String SYSTEM_PROMPTS="扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

    public LoveApp(ChatModel dashscopeChatModel) {
//        初始化基于内存的对话记忆
        String fileDir=System.getProperty("user.dir")+"chat-memory";

        ChatMemory chatMemory=new FileBasedChatMemory(fileDir);
        chatClient=ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPTS)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        //自定义日志advisor
                        new MyLoggerAdvisor()
                )
                .build();
    }
//    调用聊天接口
    public String doChat(String message,String chatId){
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String context= chatResponse.getResult().getOutput().getText();
        log.info("context:{}",context);
        return context;
    }
    record LoveReport(String title, List<String> suggestions){}

//    结构化输出
    public LoveReport doChatWithReport(String message,String chatId){
        LoveReport loveReport = chatClient.prompt()
                .system("每次对话后都要生成恋爱报告，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);
        log.info("loveReport:{}",loveReport);
        return loveReport;
    }
//    Rag知识库对话
    public  String doChatWithRag(String message,String chatId){
        message=queryRewriter.rewrite(message);
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor())
                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                .advisors(LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(loveAppVectorStore, "单身"))
                .call()
                .chatResponse();
        String context= chatResponse.getResult().getOutput().getText();
        log.info("context: {}", context);
        return context;
    }
    public  String doChatWithRagCloud(String message,String chatId){
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor())
                .advisors(loveAppRagCloudAdvisor)
                .call()
                .chatResponse();
        String context= chatResponse.getResult().getOutput().getText();
        log.info("context: {}", context);
        return context;
    }
    public  String doChatWithRagPgVector(String message,String chatId){
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor())
                .advisors(new QuestionAnswerAdvisor(pgVevctorVectorStore))
                .call()
                .chatResponse();
        String context= chatResponse.getResult().getOutput().getText();
        log.info("context: {}", context);
        return context;
    }
    public String doChatWithTools(String message,String chatId) {
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor(),new MessageChatMemoryAdvisor(chatMemory))
                .tools(allTools)
                .call()
                .chatResponse();
        String context=chatResponse.getResult().getOutput().getText();
        log.info("context: {}", context);
        return context;




    }
    public String doChatWithMcp(String message,String chatId) {
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor())
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String context=chatResponse.getResult().getOutput().getText();
        log.info("context: {}", context);
        return context;
    }
    /*流式调用，返回flux响应对象*/
    public Flux<String> doChatByStream(String message, String chatId){
       return chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvisor(),
                        new MessageChatMemoryAdvisor(chatMemory))
               .tools(toolCallbackProvider)
                .stream()
               .content();
    }
}
